<?php
namespace app\admin\controller;

use think\Db;
use think\Exception;

class Company extends Common
{
    // 企业信息管理
    public function index()
    {
        $data = [];
        //搜索
        $telephone = input('post.telephone');
        $data['telephone'] = $telephone;
        $company_name = input('post.company_name');
        $data['company_name'] = $company_name;
        //页码
        $pageNum = 1;
        if (is_numeric(input('post.pageNum'))) {
            $pageNum = input('post.pageNum');
        }
        $data['pageNum'] = $pageNum;
        //每页数量
        $numPerPage = config('num_per_page');
        $data['numPerPage'] = $numPerPage;
        $model = new \app\admin\model\Company();
        //列表数据
        $list = $model->getList($pageNum, $numPerPage, $data['company_name'], '');
        $data['list'] = $list;
        //数据总数
        $count = $model->getCount($data['company_name'], '');
        $data['count'] = $count;
        return view('', $data);
    }

    // 添加
    public function add()
    {
        $province = db('region')->where('parent_id', null)->select();
        $vehicle = db('vehicle')->select();
        $this->assign('province', $province);
        $this->assign('vehicle', $vehicle);
        return view();
    }

    // 添加可检测车型
    public function addVehicle()
    {
        $id = input('get.id');
        $data = [];
        $data['company'] = db('company')->field('id, company_name,vehicle_ids')->where('id', $id)->find();
        $vehicle_ids = explode(',', $data['company']['vehicle_ids']);
        $data['vehicle'] = db('vehicle')->select();
        foreach ($data['vehicle'] as $key => $value) {
            foreach ($vehicle_ids as $v) {
                // 循环比对车型ID与检测站可检测车型, 若相同则追加checked = true
                if ($value['id'] == $v) {
                    $data['vehicle'][$key]['checked'] = true;
                }
            }
        }
        return view('addvehicle', $data);
    }

    public function doVehicleAdd()
    {
        $data = input('post.');
        $data['vehicle_ids'] = implode(',', $data['vehicle_ids']);
        try {
            $vehicle = new \app\admin\model\Company();
            $vehicle->doAddVehicle($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '添加成功',
            'navTabId'     => 'companyManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    // 省市区联动
    public function selectajax()
    {
        $category_one = input('get.id');
        $data = [
            'parent_id' => $category_one,
        ];
        $list = db('region')->field('id,name')->where($data)->select();
        $text[] = ['', '--全部--'];
        foreach ($list as $v) {
            $text[] = [$v['id'], $v['name']];
        }
        echo json_encode($text);
    }

    // 执行添加
    public function addcompany()
    {
        $data = input('post.');
        $company_name = db("company")->where('company_name', $data['company_name'])->where('is_delete', 0)->find();
        if ($company_name) {
            return json([
                'statusCode' => 300,
                'message'    => '检车站名称已存在，请重新输入',
            ]);
        }
        $username = db("users")->where('username', $data['username'])->where('is_delete', 0)->find();
        $username2 = db("company")->where('username', $data['username'])->where('is_delete', 0)->find();
        if ($username || $username2) {
            return json([
                'statusCode' => 300,
                'message'    => '后台登录账号已存在，请重新输入',
            ]);
        }
        if (!checkTelephone($data['telephone'])) {
            return json([
                'statusCode' => 300,
                'message'    => '商家电话格式错误',
            ]);
        }
        if (!checkMobile($data['shop_leader_phone'])) {
            return json([
                'statusCode' => 300,
                'message'    => '负责人电话格式错误',
            ]);
        }
        $data['vehicle_ids'] = implode(',', $data['vehicle_ids']);
        $data['company_abbr'] = strtoupper(trim($data['company_abbr']));
        $province = get_value($data['province'], 'region', 'id', 'name', '1');
        $city = get_value($data['city'], 'region', 'id', 'name', '1');
        $district = get_value($data['district'], 'region', 'id', 'name', '1');
        $address = $province . $city . $district . $data['company_addr'];
        $url = config('tx_lbs.address'); // 腾讯地址解析
        $key = config('tx_lbs.key'); // 腾讯地址解析
        $url = sprintf($url, $address, $key);
        $result = https_request($url);
        $result = json_decode($result, true);
        if (0 == $result['status']) {
            $data['district_id'] = $result['result']['ad_info']['adcode'];
            $data['city_id'] = Db::name('base_citys')->where('id', '=', $data['district_id'])->value('parentid');
            $data['province_id'] = Db::name('base_citys')->where('id', '=', $data['city_id'])->value('parentid');
            $data['longitude'] = $result['result']['location']['lng'];
            $data['latitude'] = $result['result']['location']['lat'];
        }
        $model = new \app\admin\model\Company();
        try {
            $model->doAdd_company($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '添加成功',
            'navTabId'     => 'companyManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    // 修改
    public function modify()
    {
        $id = input('get.id');
        $this->assign('id', $id);
        $info = db('company')->where('id', $id)->find();
        $province = db('region')->where('parent_id', null)->select();
        $this->assign('province', $province);
        $city = db('region')->where('parent_id', $info['province'])->select();
        $this->assign('city', $city);
        $district = db('region')->where('parent_id', $info['city'])->select();
        $this->assign('district', $district);
        $data['info'] = $info;
        $vehicle_ids = explode(',', $info['vehicle_ids']);
        $data['vehicle'] = db('vehicle')->select();
        foreach ($data['vehicle'] as $key => $value) {
            foreach ($vehicle_ids as $v) {
                // 循环比对车型ID与检测站可检测车型, 若相同则追加checked = true
                if($value['id'] == $v){
                    $data['vehicle'][$key]['checked'] = true;
                }
            }
        }
        return view('', $data);
    }

    // 执行修改
    public function domodify()
    {
        $data = input('post.');
        $data['vehicle_ids'] = implode(',', $data['vehicle_ids']);
        $data['company_abbr'] = strtoupper(trim($data['company_abbr']));
        if (!checkTelephone($data['telephone'])) {
            return json([
                'statusCode' => 300,
                'message'    => '商家电话格式错误',
            ]);
        }
        if (!checkMobile($data['shop_leader_phone'])) {
            return json([
                'statusCode' => 300,
                'message'    => '负责人电话格式错误',
            ]);
        }
        // 腾讯地址解析 start
        $province = get_value($data['province'], 'region', 'id', 'name', '1');
        $city = get_value($data['city'], 'region', 'id', 'name', '1');
        $district = get_value($data['district'], 'region', 'id', 'name', '1');
        $address = $province . $city . $district . $data['company_addr'];
        $url = config('tx_lbs.address'); // 腾讯地址解析
        $key = config('tx_lbs.key'); // 腾讯地址解析
        $url = sprintf($url, $address, $key);
        $result = https_request($url);
        $result = json_decode($result, true);
        if (0 == $result['status']) {
            $data['district_id'] = $result['result']['ad_info']['adcode'];
            $data['city_id'] = Db::name('base_citys')->where('id', '=', $data['district_id'])->value('parentid');
            $data['province_id'] = Db::name('base_citys')->where('id', '=', $data['city_id'])->value('parentid');
            $data['longitude'] = $result['result']['location']['lng'];
            $data['latitude'] = $result['result']['location']['lat'];
        }
        // 腾讯地址解析 end
        $model = new \app\admin\model\Company();
        try {
            $model->doModify_company($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode'   => 200,
            'message'      => '修改成功',
            'navTabId'     => 'companyManage',
            'callbackType' => 'closeCurrent',
        ]);
    }

    // 执行删除
    // public function doDelete()
    // {
    //     $userId = input('get.id');
    //     $Company = new \app\admin\model\Company();
    //     try {
    //         $Company->doDelete($userId);
    //     } catch (Exception $e) {
    //         return json([
    //             'statusCode' => 300,
    //             'message'    => $e->getMessage(),
    //         ]);
    //     }
    //     return json([
    //         'statusCode' => 200,
    //         'message'    => '删除成功',
    //         'navTabId'   => 'companyManage',
    //     ]);
    // }

    // 详情
    public function detail()
    {
        $id = input('get.id');
        $info = db('company')->where('id', $id)->find();
        $province = db('region')->where('id', $info['province'])->find();
        $city = db('region')->where('id', $info['city'])->find();
        $district = db('region')->where('id', $info['district'])->find();
        $data['info'] = $info;
        $data['info']['company_addr'] = $province['name'] . $city['name'] . $district['name'] . $data['info']['company_addr'];
        return view('', $data);
    }

    /**
     * 启用-禁用
     */
    public function on_off()
    {
        $userId = input('get.id');
        $statusid = input('get.status');
        if ($statusid == 0) {
            $data['id'] = $userId;
            $data['is_use'] = 0;
            $status = "禁用";
        }
        if ($statusid == 1) {
            $data['id'] = $userId;
            $data['is_use'] = 1;
            $status = "启用";
        }
        try {
            $Company = new \app\admin\model\Company();
            $Company->editStatus($data);
        } catch (Exception $e) {
            return json([
                'statusCode' => 300,
                'message'    => $e->getMessage(),
            ]);
        }
        return json([
            'statusCode' => 200,
            'message'    => $status . '成功',
            'navTabId'   => 'companyManage',
        ]);
    }
}